package com.tedu.radisdemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.io.Serializable;

/**
 * Spring的配置类，用于配置Redis
 * 在里面维护一个RedisTemple，用于让Spring IOC容器帮我们在需要的地方自动注入该类
 */
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Serializable> initRedisTemplate(
            RedisConnectionFactory redisConnectionFactory){
        //初始化Redis的模板类
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        //为模板类设置链接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //key序列化为字符串形式
        redisTemplate.setKeySerializer(RedisSerializer.string());
        /**
         * set("张三",person)
         * class Person{
         *     private String name;
         *     private int age;
         * }
         * set 张三 {"name": "张三","age": "22"}
         *
         */
        redisTemplate.setValueSerializer(RedisSerializer.json());
        //设置hash的序列化器
        redisTemplate.setHashKeySerializer(RedisSerializer.json());
        redisTemplate.setHashValueSerializer(RedisSerializer.json());

        return redisTemplate;
    }
}
